package com.sumainfor.zuul.controller;

import com.sumainfor.common.util.FieldCheckUtil;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.util.R;
import com.sumainfor.common.wechat.WxConstant;
import com.sumainfor.common.wechat.WxEncodeUtil;
import com.sumainfor.zuul.service.SysUserTokenService;
import com.sumainfor.zuul.service.impl.WxSysUserService;
import org.apache.http.client.ClientProtocolException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 功能描述:
 *
 * @Auther: zhlu
 * @Date: 2019/1/26 17:49
 * @Description:
 */
@RestController
@RequestMapping("/wechat")
public class WechatController2 {
    @Autowired
    private SysUserTokenService sysUserTokenService;

    @Autowired
    WxSysUserService sysUserService;
    /**
     * 功能描述:
     * 生成绑定二维码
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/1/25 16:42
     */
    @GetMapping("/getQrConnectURL")
    public JsonResult getQrConnectURL(@RequestParam Map<String, Object> params) {
        JsonResult result = new JsonResult();
        if (!FieldCheckUtil.isMapFieldNotNull(params, new String[]{"url"})) {
            result.putFailed("url不能为空！");
        }
        Map<String, String> weparams = new HashMap<String, String>();
        weparams.put("appid", WxConstant.WECHATPAY_APPID);
        weparams.put("redirect_uri", WxConstant.WECHATPAY_REDIRECT_URI + params.get("url"));
        weparams.put("response_type", "code");
        weparams.put("scope", "snsapi_login");
        String wechaturl = WxEncodeUtil.getQrConnectURL(weparams);
        result.put(new HashMap<String, Object>() {{
            put("wechaturl", wechaturl);
        }});
        return result;
    }

    /**
     * 功能描述: 
     * 根据用户扫码code获取微信openID然后查询用户资料
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/1/26 19:16
     */
    @PostMapping("/getOpenIdUser")
    public Map<String, Object>getOpenIdUser(@RequestBody Map<String, Object> params) throws ClientProtocolException, IOException {
        Map<String,Object>result=sysUserService.getOpenIdUser(params);
        R r=new R();
        if(result.get("errorCode")=="0"){
            Integer UserId= (Integer) result.get("UserId");
            //生成token，并保存到数据库
            r = sysUserTokenService.createToken(UserId);
            return r;
        }else if(result.get("errorCode")=="1"){
            return R.error("账号不存在,请联系管理员!");
        }else if(result.get("errorCode")=="2"){
            return R.error("账号已被锁定,请联系管理员!");
        }
        return r;
    }
}
